package com.egglazy.Config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.egglazy.Utils.WebClientUtil;
import jakarta.annotation.PostConstruct;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class WxTokenService {

    private String token;
    private LocalDateTime expirationTime;

    @Value("${wx.token.url}")
    private String tokenUrl;

    @Value("${wx.appId}")
    private String appId;
    @Value("${wx.appSecret}")
    private String appSecret;

    // token有效期（毫秒），默认2小时
    @Value("${wx.token.validity-period}")
    private long validityPeriodMs;
    // 提前刷新阈值（毫秒），默认10分钟
    @Value("${wx.token.refresh-threshold}")
    private long refreshThresholdMs;


    /**
     * 应用启动时初始化token
     */
    @PostConstruct
    public void init() {
        refreshToken();
    }

    /**
     * 获取有效的token
     */
    public synchronized String getToken() {
        if (token == null || isTokenExpiringSoon()) {
            refreshToken();
        }
        return token;
    }

    /**
     * 检查token是否即将过期
     */
    private boolean isTokenExpiringSoon() {
        if (expirationTime == null) {
            return true;
        }
        // 如果当前时间距离过期时间小于阈值，则认为即将过期
        return LocalDateTime.now().plusNanos(refreshThresholdMs * 1000000)
                .isAfter(expirationTime);
    }

    /**
     * 定时刷新token（每小时检查一次）
     */
    @Scheduled(fixedRateString = "${wx.token.check-interval}")
    public void scheduledTokenRefresh() {
        if (isTokenExpiringSoon()) {
            refreshToken();
        }
    }

    /**
     * 刷新token
     */
    private synchronized void refreshToken() {
        try {
            // 准备请求参数
            Map<String, String> requestParams = new HashMap<>();
            requestParams.put("grant_type", "client_credential");
            requestParams.put("appid", appId);
            requestParams.put("secret", appSecret);

            String res = WebClientUtil.get(tokenUrl, requestParams, String.class).block();

            if (res != null && !res.isEmpty()) {
                JSONObject jsonObject = JSON.parseObject(res);
                // 更新token和过期时间
                this.token = jsonObject.getString("access_token");
                this.expirationTime = LocalDateTime.now().plusNanos(validityPeriodMs * 1000000);

                System.out.println("Token已刷新，将在" + expirationTime + "过期");
            }
        } catch (Exception e) {
            System.err.println("获取token失败: " + e.getMessage());
        }
    }
}
